//
//  DiaryMonthCell.swift
//  MoodDiary
//
//  Created by OVIX on 2021/1/10.
//

import UIKit

class DiaryMonthCell: UITableViewCell {
    
    @IBOutlet weak var tableView: UITableView!
    
    var monthDic: [String: [[String: Any]]]?
    
    var diaryArr: [[String: Any]]? {
        didSet {
            monthDic = [String: [[String: Any]]]()
            
            for dic in diaryArr ?? [] {
                let dayStr = NSString.getDay(dic["timeStampStr"] as! String)
                var dayDiaryArr = monthDic?[dayStr]
                if dayDiaryArr == nil {
                    dayDiaryArr = []
                }
                dayDiaryArr?.append(dic)
                monthDic?[dayStr] = dayDiaryArr
            }
            
        print("monthDic === \(monthDic)")
            
            tableView.reloadData()
        }
    }

    override func awakeFromNib() {
        super.awakeFromNib()
        
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(UINib(nibName: "DiaryDayCell", bundle: .main), forCellReuseIdentifier: "DiaryDayCell")
    }

}

extension DiaryMonthCell: UITableViewDelegate, UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int { monthDic?.keys.count ?? 0 }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        guard let monthDic = monthDic else { return 0 }
        let keys: [String] = [String](monthDic.keys)
        let key = keys[section]
        let arr = monthDic[key]
        return arr?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        guard let monthDic = monthDic else { return 0 }
        let keys: [String] = [String](monthDic.keys)
        let key = keys[indexPath.section]
        guard let arr = monthDic[key] else { return 0 }
        
        print("arr === \(arr)")
        
        var height: CGFloat = 0
        
        for dic in arr {
            if let reasonDetailStr: String = dic["reasonDetailStr"] as? String {
                if reasonDetailStr.count > 0 {
                    height += (reasonDetailStr as NSString).boundingRect(with: CGSize(width: screen_width - 75.0 - 10.0 - 30.0 * 2, height: 200.0), options: .usesLineFragmentOrigin, attributes: [:], context: nil).height + 90.0 + 25.0
                } else {
                    height += 90.0
                }
            } else {
                height += 90.0
            }
        }
        
        return height
        
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell: DiaryDayCell = tableView.dequeueReusableCell(withIdentifier: "DiaryDayCell") as! DiaryDayCell
        return cell
        
    }
    
}
